<template>
  <div class="login-container">
    <el-form ref="loginFormRef" :model="loginForm" status-icon :rules="rules" label-width="60px" class="loginForm">
      <h1>后台管理系统</h1>
      <el-form-item label="账号: " prop="userName">
        <el-input v-model="loginForm.userName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码: " prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button class="sub-btn" type="primary" @click="submitForm(loginFormRef)">登陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { InitData } from '../types/login'
import type { FormInstance } from 'element-plus'
import { login } from '../http/api'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    const data = reactive(new InitData())
    const router = useRouter()
    const rules = {
      userName: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 16, message: '长度应该在6-16个字符', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '长度应该在6-16个字符', trigger: 'blur' },
      ],
    }
    const submitForm = (loginFormRef: FormInstance) => {
      loginFormRef.validate((valid: boolean) => {
        if (valid) {
          // alert('验证完成')
          login(data.loginForm).then((res) => {
            console.log(res)
            localStorage.setItem('token', res.data.token)
            router.push('/')
          })
        }
      })
    }
    return {
      ...toRefs(data),
      rules,
      submitForm,
    }
  },
})
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  padding-top: 200px;
  box-sizing: border-box;
  background-image: url(../assets/bg.jpg);
  .loginForm {
    margin: 0 auto;
    padding: 20px;
    width: 400px;
    background: #fff;
    border-radius: 5px;
    h1 {
      text-align: center;
      padding-bottom: 30px;
    }
    .sub-btn {
      width: 100%;
    }
  }
}
</style>
